/**
 * FileDecryptor.java of project FileHashVerification created on Date: 03-Oct-2011
 * veritas
 */
package fileHashVerification.file.decryption;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
/**
 * @author veritas
 *
 */
public class FileDecryptor implements Decryptor{

	public static boolean fails = true;
	public String decrypt(FileInputStream inFile, FileOutputStream outFile,String password,String filename) throws Exception
	{
		File file = new File(filename);
		inFile = new FileInputStream(file);

                String dcrFile = file.getAbsolutePath();
                int i = dcrFile.indexOf('.');
                dcrFile = dcrFile.substring(0, i);
                dcrFile += ".dcr.txt";
                
                outFile = new FileOutputStream(dcrFile);
                
                PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey passwordKey = keyFactory.generateSecret(keySpec);

		// Read in the previouly stored salt and set the iteration count.
		byte[] salt = new byte[8];
		inFile.read(salt);
                int iterations = 100;
		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);

		// Create the cipher and initialize it for decryption.
		Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
		cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);
		
                byte[] input = new byte[64];
		int bytesRead;
		while ((bytesRead = inFile.read(input)) != -1)
		{
			byte[] output = cipher.update(input, 0, bytesRead);
			if (output != null)
				outFile.write(output);
                }
		byte[] output;
		try {
			output = cipher.doFinal();
			if (output != null)
				outFile.write(output);
                     }
		catch (IllegalBlockSizeException e) {
                   
		} catch (BadPaddingException e) {
                    
		}
		finally{
                    
			inFile.close();
			outFile.flush();
			outFile.close();
                        return dcrFile;
		}
	}
}
